<?php

declare(strict_types=1);

namespace app\admin\controller;

use app\BaseController;
use app\common\Attribute;
use think\facade\View;
use app\model\Attachment;
use app\model\Admin;
use app\model\Menu;
use Intervention\Image\ImageManager;

#[Attribute(title: "首页")]
class IndexController extends BaseController
{
    #[Attribute(isAuth: false, isPage: true, title: "首页")]
    public function index()
    {
        return View::fetch();
    }

    #[Attribute(isAuth: false, isPage: true, title: "控制台")]
    public function console()
    {
        return "欢迎使用";
    }

    #[Attribute(isAuth: false, isPage: true, title: "基本资料")]
    public function basicsInfo()
    {
        $User = session('user');
        if (!isset($User)) {
            return error('非法请求', "login/log");
        } else {
            $find = Admin::find($User["id"]);
            View::assign("find", $find);
        }
        if (request()->isPost()) {
            $all = request()->param();
            if ($all["id"] != $User['id']) {
                return error('非法操作', "login/log");
            }
            try {
                validate(\app\admin\validate\AdminValidate::class)
                    ->scene("basicsInfo")
                    ->check($all);
                if (isset($all["password"])) {
                    unset($all["password"]);
                }
                $res = Admin::update($all);
                if ($res) {
                    return success("操作成功");
                } else {
                    return error("操作失败");
                }
            } catch (\think\exception\ValidateException $e) {
                return error(msg: "验证失败", data: $e->getError());
            }
        }
        return View::fetch();
    }

    #[Attribute(isAuth: false, isPage: true, title: "修改密码")]
    public function editPwd()
    {
        $User = session('user');
        if (!isset($User)) {
            return error('非法请求', "login/log");
        }
        if (request()->isPost()) {
            $all = request()->param();
            try {
                validate(\app\admin\validate\AdminValidate::class)
                    ->scene("editPwd")
                    ->check($all);
                $all["newPwd"] = password_hash($all["newPwd"], PASSWORD_DEFAULT);
                $res = Admin::update(["id" => $User['id'], "password" => $all["newPwd"]]);
                if ($res) {
                    return success("操作成功");
                } else {
                    return error("操作失败");
                }
            } catch (\think\exception\ValidateException $e) {
                return error(msg: "验证失败", data: $e->getError());
            }
        }
        return View::fetch();
    }

    #[Attribute(isAuth: false, isPage: false, title: "菜单")]
    public function menu()
    {
        $res = Menu::where("status", "normal")->order("weigh", "desc")->select()->toArray();
        $UserAuth = session('auth');
        $arr = [];
        if ($UserAuth["rid"] > 0) {
            $AuthArr = json_decode($UserAuth["auth"], true); //已拥有的权限
            foreach ($res as $k => $file) {
                if ($file['controller'] == "" || in_array($file['controller'] . "@" . $file["method"], $AuthArr)) {
                    $arr[] = $file;
                }
            }
        } else {
            $arr = $res;
        }
        return success(data: buildTree($arr));
    }

    #[Attribute(isAuth: false, isPage: false, title: "清理缓存")]
    public function clearUrl()
    {
        $path = runtime_path("admin" . DIRECTORY_SEPARATOR . "temp");
        if (file_exists($path)) {
            // 删除文件夹
            deleteFolder($path);
        }
        return success("清理成功");
    }

    #[Attribute(isAuth: false, isPage: false, title: "附件列")]
    public function files()
    {
        if (request()->isPost()) {
            $all = request()->param();
            $data = Attachment::order("id", "desc")->paginate([
                "page" => $all["page"],
                "list_rows" => $all["limit"]
            ]);
            return json($data->toArray());
        }
    }

    #[Attribute(isAuth: false, isPage: false, title: "上传文件")]
    public function upload()
    {
        if (request()->isPost()) {
            $file = request()->file("file");
            $category = request()->post("category"); //标签
            $arr = [
                'code' => 2,
                "msg" => "文件上传失效",
            ];
            $compressSize = request()->post("compress"); //质量
            $tailorx = request()->post('tailorx');
            $tailory = request()->post('tailory');
            if (!isset($compressSize)) {
                $compressSize = 100;
            }
            $dir = "static" . "/" . 'files';
            if (!file_exists(public_path() . $dir)) {
                mkdir(public_path() . $dir, 0755, true);
            }
            // var_dump($file);
            if ($file->isValid()) {
                $fileUrl = "/" . $dir . "/"
                    . date("Ymd")
                    . "/";
                $fileName = uniqid("kllxs_", true)
                    . '.' . $file->getOriginalExtension();
                $data = [
                    "category" => $category,
                    "name" => $file->getOriginalName(),
                    "url" => $fileUrl . $fileName,
                    "type" => $file->getMime(),
                    // "size" => number_format($file->getSize() / 1048576, 2),
                    "size" => 0,
                    "spec" => $file->getOriginalExtension(),
                    "storage" => "local"
                ];
                $file = $file->move(public_path() . $fileUrl, $fileName);
                if ($file) {
                    if (
                        strpos($data["type"], "image") !== false
                        && in_array($data["spec"], ["jpg", "jpeg", "png", "gif"])
                    ) { //是图片
                        switch ($data["spec"]) {
                            case "jpg":
                            case "jpeg":
                                $image = imagecreatefromjpeg(public_path() . $fileUrl . $fileName);
                                break;
                            case "png":
                                $image = imagecreatefrompng(public_path() . $fileUrl . $fileName);
                                break;
                            case "gif":
                                $image = imagecreatefromgif(public_path() . $fileUrl . $fileName);
                                break;
                            default:
                                $image = imagecreatefromjpeg(public_path() . $fileUrl . $fileName);
                                break;
                        }
                        $width = imagesx($image); // 图片宽度
                        $height = imagesy($image); // 图片高度
                        if (isset($tailorx) && isset($tailory) && $tailorx != "" && $tailory != "") {
                            $width = (int)$tailorx;
                            $height = (int)$tailory;
                        }
                        $ImageManager = new ImageManager;
                        // 使用 Intervention/Image 进行裁剪和压缩
                        $image = $ImageManager->make(public_path() . $fileUrl . $fileName);
                        $compressedImage = $image->fit($width, $height);
                        $compressionQuality = (int)$compressSize; // 压缩质量，范围从 0 到 100
                        $compressedImage->save(public_path() . $fileUrl . $fileName, $compressionQuality);
                        $filesize = filesize(public_path() . $fileUrl . $fileName);
                        $data["size"] = number_format($filesize / 1048576, 2);
                    }
                    $res = Attachment::create($data);
                    if ($res) {
                        $arr = [
                            'code' => 1,
                            'msg' => "上传成功",
                            'url' => $fileUrl . $fileName,
                            'data' => $file
                        ];
                    } else {
                        $arr = [
                            'code' => 2,
                            "msg" => "文件写入失败",
                            "data" => $file,
                            "error" => $file
                        ];
                    }
                } else {
                    $arr = [
                        'code' => 2,
                        "msg" => "文件上传失败",
                        "data" => $file,
                        "error" => $file
                    ];
                }
            } else {
                $arr = [
                    'code' => 2,
                    "msg" => "文件无效",
                    "data" => $file
                ];
            }
            return json($arr);
        }
    }
}
